<template>
  <div class="person">
    <h2 ref="titleRef" id="titleRef">LifeCycle</h2>
    <h2>年龄：{{age}}</h2>
    <button @click="changeAge">修改年龄</button>
    <div style="padding: 10px"></div>

    <label><input type="radio" v-model="current" :value="TestA" /> TestA</label>
    <label><input type="radio" v-model="current" :value="TestB" /> TestB</label>
    <KeepAlive>
      <component :is="current"></component>
    </KeepAlive>
  </div>
</template>

<script lang="ts" setup name="LifeCycle">
import {
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
  ref,
  onErrorCaptured,
  onRenderTracked,
  onRenderTriggered
} from 'vue'
import { shallowRef } from 'vue'
import TestA from '@/components/study/TestA.vue'
import TestB from '@/components/study/TestB.vue'

const current = shallowRef(TestA)
const titleRef = ref();
console.log('setup');
// console.log('setup: titleRef', titleRef.value);
// console.log('setup: document', document.getElementById('titleRef'))
onBeforeMount(() => {
  console.log('onBeforeMount ===> 相当于 vue2.x 中 beforeMount')
})
onMounted(() => {
  // console.log('onMounted: titleRef', titleRef.value)
  // console.log('onMounted: document', document.getElementById('titleRef'));
  console.log('onMounted ===> 相当于 vue2.x 中 mounted')
})

// 注意，onBeforeUpdate 和 onUpdated 里面不要修改值
onBeforeUpdate(() => {
  console.log('onBeforeUpdate ===> 相当于 vue2.x 中 beforeUpdate')
})

onUpdated(() => {
  console.log('onUpdated ===> 相当于 vue2.x 中 updated')
})

onBeforeUnmount(() => {
  console.log('onBeforeUnmount ===> 相当于 vue2.x 中 beforeDestroy')
})

onUnmounted(() => {
  console.log('onUnmounted ===> 相当于 vue2.x 中 destroyed')
})

onErrorCaptured((err, vm, info) => {
  console.log('onErrorCaptured ===> 相当于 vue2.x 中 errorCaptured')
  console.error(`捕获到错误：${err.toString()}\n信息：${info}`);
  return false;
});

onRenderTracked((event) => {
  // 当响应式依赖被跟踪时，会调用这个回调
  console.log(`Tracked`, event);
});

onRenderTriggered((event) => {
  // 当组件重新渲染时，会调用这个回调
  console.log(`Triggered`, event);
});

let age = ref(18);
function changeAge() {
  age.value += 1;
}
</script>
